//引入axios
import axios from "axios"
/**
 * 设置请求时间
 */
axios.defaults.timeout = 3000
/**
 * 设置请求地址
 */
axios.defaults.baseURL = 'http://tian.tianguixing.com:4001/api/private/v1'
//引入element提示和loading加载
import { ElMessage, ElLoading } from 'element-plus'
/**
 * 设置请求拦截器
 */
let Loading;
axios.interceptors.request.use(confirg => {
  let token = sessionStorage.getItem('token')
  //请求头添加token
  confirg.headers.Authorization = token
  //开启loading加载
 Loading=ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  return confirg

}, error => Promise.reject(error))


/**
 * 设置相应拦截器
 */
axios.interceptors.response.use(response => {
    //销毁loading
  Loading.close()
  const res = response.data
  //判断数据请求结果状态
  if (res.meta.status == 200 || res.meta.status == 201) {
    ElMessage({
      message: '获取成功',
      type: 'success',
    })
  }
//返回请求数据
  return res
}, error => {
  const msg = error.toString()
  if (msg.includes('timeout')) {
    ElMessage({
      message: '请求超时',
      type: 'error',
    })
    return Promise.reject(error)
  }
  if (msg.includes('Network Error')) {
    ElMessage({
      message: '网络错误，请检查网络',
      type: 'error',
    })
    return Promise.reject(error)
  }
  const { status } = error.response
  switch (status) {
    case 401:
      ElMessage({
        message: '登录过期请重新登陆',
        type: 'error',
      })
      break
    case 404:
      const { msg } = error.response.data
      ElMessage({
        message: msg + '接口不存在',
        type: 'error',
      })
      break
    case 500:
      ElMessage({
        message: '服务器内部错误',
        type: 'error',
      })
      break
    default:
      break
  }
  return Promise.reject(error)
})

export default axios